package com.tarena.luban.test.repository.impl;

import com.tarena.luban.test.bo.WorkerBO;
import com.tarena.luban.test.dao.WorkerDao;
import com.tarena.luban.test.repository.WorkerRepository;
import com.tarena.luban.test.repository.converter.WorkerConverter;
import com.tarena.passport.protocol.LoginUser;
import com.tarena.passport.sdk.context.SecurityContext;
import com.tarena.tp.luban.worker.po.Worker;
import com.tarena.tp.luban.worker.server.common.enums.AccountStatusEnum;
import com.tarena.tp.luban.worker.server.common.enums.AuditStatusEnum;
import com.tarena.tp.luban.worker.server.common.enums.StatusEnum;
import com.tarena.tp.luban.worker.server.dto.param.WorkerCreateParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

@Repository
@Slf4j
public class WorkerRepoImpl extends RedisCacheEntry<WorkerBO> implements WorkerRepository {
    @Autowired(required = false)
    private WorkerDao workerDao;
    @Override
    public void deleteWorker(Long userId) {
        //调用删除
        workerDao.delete(userId);
        String key="luban:worker:"+userId;
        delete(key);
    }

    @Override
    public Long saveWorker(WorkerCreateParam workerCreateParam) {
        //转化
        Worker worker=param2do(workerCreateParam);
        log.info("当前新增的worker的id:{}",worker.getId());
        workerDao.save(worker);
        //新增结束 ,利用mybatis自增回填特性,可以在worker中获取新增数据之后的id值
        log.info("新增完成的worker的id:{}",worker.getId());
        return worker.getId();
    }
    @Autowired
    private WorkerConverter workerConverter;
    @Override
    public WorkerBO findWorker(Long userId) {
        String key="luban:worker:"+userId;
        Boolean exists = exists(key);
        WorkerBO workerBO =null;
        if (!exists){
            log.info("缓存没命中,读取数据库数据,key:{}",key);
            String lockKey=key+".lock";
            Boolean tryLock = tryLock(lockKey, "");
            try{
                if (tryLock){
                    //说明当前线程可以执行数据库查询
                    Worker worker=workerDao.selectWorkerByUserId(userId);
                    workerBO = workerConverter.po2bo(worker);
                    saveCache(key,workerBO,24L, TimeUnit.HOURS);
                }else{
                    //等待2秒钟
                    Thread.sleep(2000);
                    workerBO=getCache(key);
                }
            }catch (Exception e){

            }finally {
                delete(lockKey);
            }
        }else {
            workerBO=getCache(key);
            log.info("缓存命中,读取缓存数据,key:{},value:{}",key,workerBO);
        }
        return workerBO;
    }

    private Worker param2do(WorkerCreateParam workerCreateParam) {
        Worker worker=new Worker();
        //判断参数是否是空
        if (workerCreateParam==null){
            return worker;//属性是null
        }
        //先将param里的所有可用的属性做转化
        BeanUtils.copyProperties(workerCreateParam,worker);
        //通用字段6个属性 没有值 gmt_create gmt_modified modified_user_id create_user_id modified_user_name create_user_name
        worker.setGmtCreate(System.currentTimeMillis());//当前系统毫秒数
        worker.setGmtModified(worker.getGmtCreate());
        LoginUser loginToken = SecurityContext.getLoginToken();
        worker.setCreateUserId(loginToken.getUserId());
        worker.setCreateUserName(loginToken.getUserName());
        worker.setModifiedUserId(loginToken.getUserId());
        worker.setModifiedUserName(loginToken.getUserName());
        //三个状态 给初始值 师傅状态(启用1禁用0) 审核状态(驳回0,已通过1,未审核2,未入住3) 平台账号的认证状态(未认证0,已认证1)
        worker.setStatus(StatusEnum.NORMAL.getValue());
        worker.setAuditStatus(AuditStatusEnum.UNAUDITED.getValue());
        worker.setCertStatus(AccountStatusEnum.DISABLE.getValue());
        return worker;
    }
}
